<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Fair Urban</title>
</head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {
	height: 100%
}

body {
	height: 100%;
	margin: 0;
	padding: 0
}

#map_canvas {
	height: 100%
}

.loginform
{
	background-color:white;
}

.clsTable
{
	border: 0;
	border-collapse:separate; 
	border-spacing:2em;
	border-width: 1px; 
	border-color:#000000; 
	border-style: solid;
}

.reqVal
{
	color: red;
	display: none;
}
</style>
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700"
	rel="stylesheet" type="text/css" />
<link href="css/default.css" rel="stylesheet" type="text/css"
	media="all" />

<script type="text/javascript"
	src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCg0FRVSu5XHjjkG1NV1tev04MaGOTg5Jo&sensor=false"></script>
<script type="text/javascript"
	src="http://code.jquery.com/jquery-1.8.2.min.js"></script>

<script type="text/javascript" src="js/jquery.lightbox_me.js"></script>

<script type="text/javascript">

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

var markersArray = [];

function clearOverlays() {
	  for (var i = 0; i < markersArray.length; i++ ) {
	    markersArray[i].setMap(null);
	  }
	}

function doNothing() {
}

function bindInfoWindow(marker, map, infoWindow, html) {
	markersArray.push(marker);
	google.maps.event.addListener(marker, 'click', function() {
		infoWindow.setContent(html);
		infoWindow.open(map, marker);
	});
}

function codeLatLng(latLng) {
	    var input = latLng;
	    var latlngStr = input.split(",",2);
	    var lat = parseFloat(latlngStr[0]);
	    var lng = parseFloat(latlngStr[1]);
	    var latlng = new google.maps.LatLng(lat, lng);
	    geocoder.geocode({'latLng': latlng}, function(results, status) {
	      if (status == google.maps.GeocoderStatus.OK) {
	        if (results[0]) {
	          $('#lblAddress').html(results[0].formatted_address);
	        }
	      } else {
	        alert("Adres bulma hatası: " + status);
	      }
	    });
}

// Set the Map variable
var map;
geocoder = new google.maps.Geocoder();
function initialize() {
	var myOptions = {
		zoom : 18,
		mapTypeId : google.maps.MapTypeId.HYBRID,
		scrollwheel: false
	};

	var infoWindow = new google.maps.InfoWindow;

	var markerImg = new google.maps.MarkerImage(
			'images/markers/marker2.png',
			// This marker is 129 pixels wide by 42 pixels tall.
			new google.maps.Size(129, 42),
			// The origin for this image is 0,0.
			new google.maps.Point(0, 0),
			// The anchor for this image is the base of the flagpole at 18,42.
			new google.maps.Point(18, 42));

	var entryId = getParameterByName('id');
	
	if(entryId == "")
	{
		window.location.replace("default.html");
	}
	
	var getEntryByIdUrl = "./service/entries/" + entryId;
	var coordX = 0;
	var coordY = 0;
	
	$.getJSON(getEntryByIdUrl, function(data) {
		
		var myData = data['data'][0];
		
		var priority = "<font color='olive'>Düşük</font>";
		if(myData.priority == "Low")
		{
			priority = "<font color='olive'>Düşük</font>";
		}
		else if(myData.priority == "High")
		{
			priority = "<font color='orange'>Yüksek</font>";
		}
		else if(myData.priority == "Critical")
		{
			priority = "<font color='red'>Kritik</font>";
		}
		
		var fixed = "<font color='red'>Henüz düzeltilmedi</font>";
		if(myData.fixed == false)
		{
			fixed = "<font color='red'>Henüz düzeltilmedi</font>";
			$('#chkFixed').prop('checked', false);
		}
		else if(myData.fixed == true)
		{
			fixed = "<font color='green'>Düzeltildi</font>";
			$('#chkFixed').prop('checked', true);
		}
		
		IsSameUser(myData.userName);
		
	    var comment = myData.comment;
		var upVote = myData.upVoteCount;
		var downVote = myData.downVoteCount;
		var user = myData.userName;
		var image = myData.imageMeta;
		var comments = myData.comments;
		var category = myData.category;
		var extraKey = '';
		var extraValue = '';
		var extraBoundary = '';
		var catKey = '';
		var catBoundary = '';
		var catTitle = category.title;
		
		if(myData.extra != null)
		{
			extraKey = myData.extra.key;
			extraValue = myData.extra.value;
			extraBoundary = myData.extra.boundary;
			$('#lblValue').html(extraValue);
			$('#lblDetailKey').html(extraKey);
		}
		else
		{
			$('#lblValue').html("Detay girilmemiş");
			$('#lblDetailKey').html("");
		}
		
		if(category.extra != null)
		{
			catKey = category.extra.key;
			catBoundary = category.extra.boundary;
			$('#lblRequired').html(catBoundary + " " + catKey);
			$('#lblDetailKey2').html(catKey);
		}
		
		else
		{
			$('#lblRequired').html("-");
			$('#lblDetailKey2').html("-");
		}
		
		coordX = myData.coordX;
		coordY = myData.coordY;
		var point = new google.maps.LatLng(parseFloat(coordX), parseFloat(coordY));
		var html = "<b>Koordinatlar: </b> " + coordX + " , " + coordY;
		var marker = new google.maps.Marker({
			map : map,
			position : point,
			icon : markerImg
		});
				
		bindInfoWindow(marker, map, infoWindow, html);

		codeLatLng(coordX + ","+ coordY);
		
		var allComments = "</br></br>";
		if(comments.length == 0)
		{
			allComments = "Hiç yorum girilmemiş";
		}
		else {
			$.each(comments,function(index,element) {
				var aCom = "<i>(" + element.insertDate + ", " + element.username + ")</i>&nbsp;&nbsp;" + element.text + "</br></br>";
				allComments = allComments + aCom;
			});
		}

		$('#lblCategory').html(catTitle);
		$('#spnComments').html(allComments);
		$('#lblStatus').html(fixed);
		$('#lblPriority').html(priority);
		$('#lblComment').html(comment);
		$('#lblUpVote').html(upVote);
		$('#lblDownVote').html(downVote);
		$('#lblUser').html(user);
		$('#hdnUpVote').val(upVote);
		$('#hdnDownVote').val(downVote);
		$('#lnkImage').attr('href', image); //todo: uncomment this for production
		$('#imgEntry').attr('src', image); //todo: uncomment this for production

		// Set the center of the map
		var pos = new google.maps.LatLng(coordX, coordY);
		map.setCenter(pos);
	 });
	
	map = new google.maps.Map(document.getElementById('map_canvas'),
			myOptions);

	function infoCallback(infowindow, marker) {
		return function() {
			infowindow.open(map, marker);
		};
	}
};

// Initializes the Google Map
google.maps.event.addDomListener(window, 'load', initialize);

var voteUrl = "./service/entries/thumbs";

function voteUp() {
	var loggedIn = $('#loggedMu').val();
	if(loggedIn == "false")
	{
		alert('Oy kullanabilmek için giriş yapmalısınız!');
		return;
	}
	var entryId = getParameterByName('id');
	if($('#lnkUpVote').hasClass("disabled")){return};
	$.ajax({
	    url: voteUrl,
	    type: 'post',
	    data: JSON.stringify({entryId:entryId,up:true}),
	    dataType: 'json',
	    contentType: "application/json;charset=utf-8",
	    success: function(data) {
	        if(data.resultStatus == "SUCCESS")
	        {
	        	var upp = $('#lblUpVote').text();
			    $('#lblUpVote').text(parseInt(upp) + 1);
			    $('#lnkUpVote').removeAttr("href");
			    $('#lnkUpVote').addClass("disabled");
			    alert('Bu kayıt için "acil" oyu verdiniz.');
	        }
	        else if(data.resultStatus == "FAILURE" && data.resultId == 2)
	        {
	        	alert('Bu kayıt için daha önce oy vermişsiniz, başka oy veremezsiniz.');
	        }
	        else
	        {
	        	alert('Oy verirken bir hata oluştu, lütfen tekrar deneyin.');
	        }
	    },
	    error: function(data) {
	    	alert('Oy verirken bir hata oluştu, lütfen tekrar deneyin.');
	    }
	})
};

function voteDown() {
	var loggedIn = $('#loggedMu').val();
	if(loggedIn == "false")
	{
		alert('Oy kullanabilmek için giriş yapmalısınız!');
		return;
	}
	var entryId = getParameterByName('id');
	if($('#lnkDownVote').hasClass("disabled")){return};
	$.ajax({
		url: voteUrl,
	    type: 'post',
	    data: JSON.stringify({entryId:entryId,up:false}),
	    dataType: 'json',
	    contentType: "application/json;charset=utf-8",
	    success: function(data) {
	        if(data.resultStatus == "SUCCESS")
	        {
	        	var dnn = $('#lblDownVote').text();
				$('#lblDownVote').text(parseInt(dnn) + 1);
				$('#lnkDownVote').removeAttr("href");
				$('#lnkDownVote').addClass("disabled");
				alert('Bu kayıt için "bekleyebilir" oyu verdiniz.');
	        }
	        else if(data.resultStatus == "FAILURE" && data.resultId == 2)
	        {
	        	alert('Bu kayıt için daha önce oy vermişsiniz, başka oy veremezsiniz.');
	        }
	        else
	        {
	        	alert('Oy verirken bir hata oluştu, lütfen tekrar deneyin.');
	        }
	    },
	    error: function(data) {
	    	alert('Oy verirken bir hata oluştu, lütfen tekrar deneyin.');
	    }
	})
};

var addCommentUrl = "./service/comments/add";
var isLoggedInUrl = "./service/login/status";
var saveDetailUrl = "./service/entries/edit";
var isFixedUrl = "./service/entries/edit/status";

function addComment() {
	
	var txtVal = $('#txtComment').val();
	if(txtVal == '')
	{
		return;
	}
	
	var loggedIn = $('#loggedMu').val();
	if(loggedIn == "false")
	{
		alert('Yorum ekleyebilmek için giriş yapmalısınız!');
		return;
	}
	
	var entryId = getParameterByName('id');
	$.ajax({
	    url: addCommentUrl,
	    type: 'post',
	    data: JSON.stringify({entryId:entryId, text:txtVal}),
	    dataType: 'json',
	    contentType: "application/json;charset=utf-8",
	    beforeSend : function() {
			$("#spinner2").show();
		},
		complete : function() {
			$("#spinner2").hide();
		},
	    success: function(data) {
	        if(data.resultStatus == "success")
	        {
	        	alert('Yorumunuz kaydedildi, teşekkürler!');
	        	$('#txtComment').val('');
	        	
	        	//////////update comments list
	        	var entryId = getParameterByName('id');
	        	var getEntryByIdUrl = "./service/entries/" + entryId;
	        	
	        	$.getJSON(getEntryByIdUrl, function(data) {
	        		var comments = data['data'][0].comments;
	        		var allComments = "</br></br>";
	        		$.each(comments,function(index,element) {
	        			var aCom = "<i>(" + element.insertDate + ", " + element.username + ")</i>&nbsp;&nbsp;" + element.text + "</br></br>";
	        			allComments = allComments + aCom;
	        		});
	        		$('#spnComments').html(allComments);
	        	});
	        	////////// 	
	        }
	        else
	        {
	        	alert('Yorumunuz kaydedilirken bir hata oluştu, lütfen daha sonra tekrar deneyin.');
	        }
	    },
	    error: function(data) {
	    	alert('Yorumunuz kaydedilirken bir hata oluştu, lütfen daha sonra tekrar deneyin.');
	    }
	})
};

function saveDetail() {
	
	var txtVal = $('#txtDetail').val();
	if(txtVal == '')
	{
		return;
	}
	
	var loggedIn = $('#loggedMu').val();
	if(loggedIn == "false")
	{
		alert('Detay ekleyebilmek için giriş yapmalısınız!');
		return;
	}
	
	var entryId = getParameterByName('id');
	$.ajax({
	    url: saveDetailUrl,
	    type: 'post',
	    data: JSON.stringify({entryId:entryId, value:txtVal}),
	    dataType: 'json',
	    contentType: "application/json;charset=utf-8",
	    beforeSend : function() {
			$("#spinner").show();
		},
		complete : function() {
			$("#spinner").hide();
		},
	    success: function(data) {
	        if(data.resultStatus == "Success")
	        {
	        	alert('Detay kaydedildi, teşekkürler!');
	        	$('#txtDetail').val('');
	        	$('#lblValue').html(txtVal);
	        }
	        else
	        {
	        	alert('Detay kaydedilirken bir hata oluştu, lütfen daha sonra tekrar deneyin.');
	        }
	    },
	    error: function(data) {
	    	alert('Detay kaydedilirken bir hata oluştu, lütfen daha sonra tekrar deneyin.');
	    }
	})
};


function entryFixed() {
	
	var fixed = $('#chkFixed').is(':checked');
	var entryId = getParameterByName('id');
	
	$.ajax({
	    url: isFixedUrl,
	    type: 'post',
	    data: JSON.stringify({entryId:entryId, value:fixed}),
	    dataType: 'json',
	    contentType: "application/json;charset=utf-8",
	    beforeSend : function() {
			$("#spinner3").show();
		},
		complete : function() {
			$("#spinner3").hide();
		},
	    success: function(data) {
	        if(data.resultStatus == "Success")
	        {
	        	var fixedTxt = "<font color='red'>Henüz düzeltilmedi</font>";
	    		if(fixed == false)
	    		{
	    			fixedTxt = "<font color='red'>Henüz düzeltilmedi</font>";
	    		}
	    		else if(fixed == true)
	    		{
	    			fixedTxt = "<font color='green'>Düzeltildi</font>";
	    		}
	    		
	    		$('#lblStatus').html(fixedTxt);
	        }
	        else
	        {
	        	alert('Bir hata oluştu, lütfen daha sonra tekrar deneyin.');
	        }
	    },
	    error: function(data) {
	    	alert('Bir hata oluştu, lütfen daha sonra tekrar deneyin.');
	    }
	})
};
</script>

<script type="text/javascript">

var voteUrl = "./service/entries/thumbs";
var isLoggedInUrl = "./service/login/status";
var logOutUrl = "./j_spring_security_logout";

	$(document).ready(function() {
		
		IsLoggedIn();

		$('#spnLogin').click(function(e) {
		    $('#divlogin').lightbox_me({
		        centered: true, 
		        onLoad: function() { 
		            $('#sign_up').find('input:first').focus()
		            }
		        });
		    e.preventDefault();
		});
		
		//testuser - swe574TEST!
		$('#frmlogin').submit(function() {
			
			if($('#username').val() == "" || $('#password').val() == "")
			{
				if($('#username').val() == ""){$('#reqUser').show();}else{$('#reqUser').hide();}
				if($('#password').val() == ""){$('#reqPass').show();}else{$('#reqPass').hide();}
				return false;
			}
			else
			{
				//alert($("#frmlogin").serialize())
				$.ajax({
					type: 'POST',
					data: $("#frmlogin").serialize(),
		          	url: './service/login/sigin',
		            success: function(msg,textStatus) {
		            	//alert("Başarıyla giriş yaptınız!");
		            	//$('#spnLogout').show();
	 					//$('#spnLogin').hide();
		            	$('#divlogin').trigger('close');
		            	IsLoggedIn();
		            },
		            error:function(jqXHR, textStatus, errorThrown){
			          alert("Yanlış kullanıcı adı/şifre, lütfen tekrar deneyiniz.");
		              //alert(errorThrown);
		            }
		        });
				  return false;
			}	
		});
	});
	
	function IsSameUser(username) {
		$.ajax({
			url : isLoggedInUrl,
			type : 'get',
			success: function(msg){
				if(msg.loggedIn == true && msg.username == username)
					{
						$('#divFixed').show();
					}
				else
					{
						//task 46: show isFixed checkbox to all users.
						$('#divFixed').show();
						//$('#divFixed').hide();
					}
			},
			error: function(){}
		})
	}
	
	function IsLoggedIn() {
		$.ajax({
			url : isLoggedInUrl,
			type : 'get',
			success: function(msg){
				if(msg.loggedIn == true)
					{
						$('#welcomeText').show().html('Hoşgeldin ' + msg.username + '!');
	 					$('#spnLogout').show();
	 					$('#spnLogin').hide();
	 					$('#liNewEntry').show();
						$('#loggedMu').val('true');
					}
				else
					{
						$('#welcomeText').hide();
						$('#spnLogin').show();
						$('#spnLogout').hide();
						$('#liNewEntry').hide();
						$('#loggedMu').val('false');
					}
			},
			error: function(){}
		})
	};

	
	function logOut() {
		$.ajax({
			url : logOutUrl,
			type : 'get',
			complete: function(xhr, statusText){
				if(xhr.status == 200)
				{
	 				alert("Başarıyla çıkış yaptınız!");
	 				IsLoggedIn();
				}
				else
				{
					$('#spnLogout').show();
					$('#spnLogin').hide();
				}
		    }
		})
	};
</script>

<body>
	<input type="hidden" name="loggedMu" id="loggedMu" value="false">
<div class="loginform" style="display: none; border:#111" id="divlogin">
<form action="./service/login/sigin" accept-charset="UTF-8" method="post" id="frmlogin">
    <table class="clsTable">
       <tr>
         <td colspan="2"><span style="font-size: large;">Siteye giriş yapın</span></td>
       </tr>
       <tr>
         <td><label for="username">Kullanıcı adı:<span class="reqVal" id="reqUser">&nbsp;*</span></label></td>
         <td> <input type="text" maxlength="60" name="username" id="username" size="15" value="" class="required" style="float: right"></td>
       </tr>
       <tr>
         <td><label for="password">Şifre:<span class="reqVal" id="reqPass">&nbsp;*</span></label></td>
         <td> <input type="password" name="password" id="password" maxlength="60" size="15" class="required" style="float: right"></td>
       </tr>
       <tr>
         <td><input type="submit" name="submit" id="submit" value="Giriş" style="font-weight: bold;"></td>
         <td></td>
       </tr>
       <tr>
         <td><a href="register.html" title="Üye olun!" style="font-size: 14px;">Kaydol</a></td>
         <td></td>
       </tr>
    </table>
	<input type="hidden" name="form_build_id" id="form-c1062bd63291587f665fe24a402917e9" value="form-c1062bd63291587f665fe24a402917e9">
	<input type="hidden" name="form_id" id="edit-user-login-block" value="user_login_block">
</form>
</div>
	<div id="wrapper" class="container">
		<div id="header">
			<div id="logo">
				<a href="default.html"><img src="images/logo.png" width="25%;" style="float: left"></a>
				<h1 style="margin-top: 10px">  
					<a href="default.html">&nbsp;FAIR URBAN</a>
				</h1>
				<!-- 			<p>Alt Başlık</p> -->
			</div>
			<div id="menu">
				<ul>
					<li><a href="default.html">Ana Sayfa</a></li>
					<li><a href="about.html">Hakkımızda</a></li>
					<li id="liNewEntry"><a href="new.html">Yeni Ekle</a></li>
					<li><a href="report.html">Raporlama</a></li>
					<li><a id="spnLogin" style="display: none" href="javascript:;">GIRIS</a>
						<a id="spnLogout" style="display: none" href="javascript:;" onclick="logOut();" >ÇIKIS</a>
					</li>
				</ul>
			</div>
			<span style="display: none; float: right; margin-right: 20px; margin-top: 10px; font-weight: bold;" id="welcomeText"></span>
		</div>
		<div id="page" style="padding: 20px 0 0;">
			<div id="content" style="width: 900px;">
			<div style="float: left; width: 400px; margin-bottom: 20px;">
						<input type="hidden" id="hdnUpVote" value="0" name="hdnUpVote" />
						<input type="hidden" id="hdnDownVote" value="0" name="hdnUpVote" />
						<a target="_blank" id="lnkImage" href="#"> <!--images/generic.png-->
							<img border="1" width="50%" height="50%" 
								src="" id="imgEntry">
							</a>
<!-- 						<p style="height: 10px;"></p> -->
<!-- 						<span style="font-weight: bold;">Öncelik:</span> -->
<!-- 						<span id="lblPriority"></span> -->
						<p style="height: 10px;"></p>
						<span style="font-weight: bold;">Durum:</span>
						<span id="lblStatus"></span>
						<div id="divFixed" style="display:none;">
							<input type="checkbox" id="chkFixed"/><label for="chkFixed">Düzeltildi</label>
							&nbsp;<input type="button" value="Gönder" id="btnFixed" onclick="entryFixed();"/>
							<span id="spinner3" class="spinner" style="display:none;"><img id="img-spinner" src="images/spinner.gif" alt="Kaydediliyor..."/></span>
						</div>	
						<p style="height: 10px;"></p>
						<span style="font-weight: bold;">Girişi yapan:</span>
						<span id="lblUser"></span>
						<p style="height: 10px;"></p>
						<span style="font-weight: bold;">Adres:</span>
						<span id="lblAddress"></span>
						<p style="height: 10px;"></p>
						<span style="font-weight: bold;">Açıklama:</span>
						<span id="lblComment"></span>
						<p style="height: 20px;"></p>
						
						<span style="font-weight: bold;">Kategori:</span>
						<span id="lblCategory"></span>				
						<p style="height: 5px;"></p>						
						<span style="font-weight: bold;">Mevcut durum:</span>
						<span id="lblValue"></span>&nbsp;<span id="lblDetailKey"></span>
						<p style="height: 5px;"></p>	
						<span style="font-weight: bold;">Olması gereken üst sınır:</span>
						<span id="lblRequired"></span>								
						<p style="height: 5px;"></p>
						<span style="font-weight: bold;">Veriyi düzelt:</span>
						<input type="text" id="txtDetail" style="width: 50px;"/>&nbsp;<span id="lblDetailKey2"></span>
						&nbsp;&nbsp;<input type="button" id="btnDetail" value="Gönder" onclick="saveDetail();"/>	
						<span id="spinner" class="spinner" style="display:none;"><img id="img-spinner" src="images/spinner.gif" alt="Kaydediliyor..."/></span>						
						<p style="height: 20px;"></p>
						
						<span style="font-weight: bold;">"Acil" Oy:</span>
						<span id="lblUpVote"></span>&nbsp;&nbsp;&nbsp;
						<span style="font-weight: bold;">"Bekleyebilir" Oy:</span>
						<span id="lblDownVote"></span>
						<p style="height: 10px;"></p>&nbsp;&nbsp;
						<a id="lnkUpVote" href="javascript:voteUp();"><img width="50" height="50" 
							src="images/upArrow.png" title="'Acil' oy ver"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<a id="lnkDownVote" href="javascript:voteDown();"><img width="50" height="50" 
							src="images/downArrow.png" title="'Bekleyebilir' oy ver"></a>&nbsp;&nbsp;&nbsp;
						<p style="height: 20px;"></p>
						<span style="font-weight: bold;">Yorumlar:</span>
						<span id="spnComments"></span>
						<p style="height: 10px;"></p>
						<span style="font-weight: bold;">Yorumunuz:</span>
						<textarea class="comment" name="txtComment"
							id="txtComment" cols="20" rows="4" style="margin-bottom: -45px;"></textarea>
						<input type="button" id="btnCommentSave" name="btnCommentSave" value="Gönder"
							onclick="addComment();" />
						<span id="spinner2" class="spinner" style="display:none;"><img id="img-spinner" src="images/spinner.gif" alt="Kaydediliyor..."/></span>	
						<p style="height: 60px;"></p>	
						<a href="javascript: window.history.go(-1)" style="font-weight:bold; 
							text-decoration: underline; color: #2AA8D2; font-size: 14px;"><--Geri</a>					
					</div>
					<div id="map_canvas" style="width: 480px; height: 480px; 
					margin-right: 0px; float: right; margin-bottom: 25px;"></div>
			</div>	
		</div>
	</div>
	<p style="height: 20px"></p>
</body>
</html>
